import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Space, Modal, Steps, Card, Upload, message, Radio, Tag, Row, Col, Checkbox, List, Spin } from 'antd';
import { InboxOutlined, ArrowLeftOutlined, DeleteOutlined, ScissorOutlined, LoadingOutlined } from '@ant-design/icons';
import { Knowledge, Vector } from '../store/vectorTypes';
import UploadAttachment from '@/components/upload/UploadAttachment';
import { getContentByFileId } from '@/apis/public/fileUpDownload';
import RichEditor from '@/components/editor/editor';
import { createKnowledgeItem } from '@/apis/backhub/knowledgeItem';

const { Step } = Steps;

interface VectorItemFormProps {
  visible: boolean;
  onCancel: () => void;
  onSubmit: (values: any) => void;
  currentTable: Knowledge | null;
  vector: Vector | null;
}

// 规则项接口
interface RuleItem {
  id: string;
  rule: string;
  description: string;
  position: 'before' | 'after' | 'split';
}

// 文件上传组件
const FileUploadStep: React.FC<{
  fileContent: string;
  setFileInfo: React.Dispatch<React.SetStateAction<{ content: string; name: string }>>;
}> = ({ fileContent, setFileInfo }) => {

  // 上传成功回调
  const handleUploadSuccess = async (resp: any) => {
    if (resp && resp.data && resp.data.status && resp.data.data.page && resp.data.data.page.length > 0) {
      const fileMeta = resp.data.data.page[0];
      const contentRes = await getContentByFileId({
        id: fileMeta.id,
        fileName: fileMeta.fileName || '',
        filePath: fileMeta.filePath || '',
        directoryId: fileMeta.directoryId || 0,
        userId: fileMeta.userId || 0,
        pageNo: 1,
        pageSize: 100,
        html: ''
      });
      if (contentRes.status && contentRes.data && contentRes.data.success) {
        setFileInfo(pre => ({ ...pre, content: contentRes.data.content, name: fileMeta.fileName || '' }));
        message.success('文件内容获取成功');
      } else {
        message.error('获取文件内容失败');
      }
    } else {
      message.error('文件上传异常');
    }
  };

  return (
    <div style={{ padding: '40px 0' }}>
      <UploadAttachment
        scene="vector"
        onUploadSuccess={handleUploadSuccess}
        maxFileSize={50 * 1024 * 1024}
        showUploadList={true}
        dragger={true}
        child={<>
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">点击这里上传文件</p>
          <p className="ant-upload-hint">
            支持的文件格式为 pdf (含扫描件)、txt、docx、ppt、pptx、md、html、xls、xlsx、csv、doc；每个文件最大支持50mb；pdf支持渐源定位。
          </p>
        </>}
      />
      {fileContent && (
        <div style={{ marginTop: 16, maxHeight: 512, }}>
          <h3>文档内容预览：</h3>
          <div style={{ maxHeight: 512, overflow: 'hidden', overflowY: 'auto' }}>
            <RichEditor
              value={fileContent}
              readOnly={true}
              style={{ overflow: 'auto', padding: 8, borderRadius: 4 }}
            />
          </div>

        </div>
      )}
    </div>
  );
};

// 分段策略组件
const SplitStrategyStep: React.FC<{
  vector: Vector | null;
  ruleList: RuleItem[];
  setRuleList: React.Dispatch<React.SetStateAction<RuleItem[]>>;
  keepImages: boolean;
  setKeepImages: React.Dispatch<React.SetStateAction<boolean>>;
  enableOCR: boolean;
  setEnableOCR: React.Dispatch<React.SetStateAction<boolean>>;
  enableFormula: boolean;
  setEnableFormula: React.Dispatch<React.SetStateAction<boolean>>;
}> = ({
  vector,
  ruleList,
  setRuleList,
  keepImages,
  setKeepImages,
  enableOCR,
  setEnableOCR,
  enableFormula,
  setEnableFormula
}) => {
    const [customRule, setCustomRule] = useState('');
    const [rulePosition, setRulePosition] = useState<'before' | 'after' | 'split'>('split');

    // 添加规则
    const addRule = (rule: string, description?: string) => {
      if (!rule) return;

      const newRule: RuleItem = {
        id: `rule-${Date.now()}`,
        rule,
        description: description || `${rule} ${rulePosition === 'before' ? '前' : rulePosition === 'after' ? '后' : ''}切分`,
        position: rulePosition
      };

      setRuleList([...ruleList, newRule]);
      setCustomRule('');
    };

    // 删除规则
    const deleteRule = (id: string) => {
      setRuleList(ruleList.filter(item => item.id !== id));
    };

    // 添加预定义规则
    const addPredefinedRule = (rule: string, description: string) => {
      addRule(rule, description);
    };

    return (
      <div style={{ padding: '20px 0' }}>
        <div style={{ margin: '0 auto', width: 747 }}>
          <Card title="切分通用设定" style={{ marginBottom: 20 }}>
            <div style={{ display: 'flex', }}>
              <Form.Item label="预期切分长度" name="maxParagraphSize" initialValue={vector?.maxParagraphSize || 1000}>
                <Input addonAfter="字符" type="number" />
              </Form.Item>
              <Form.Item label="重叠区长度" name="maxOverlapSize" initialValue={vector?.maxOverlapSize || 0} style={{ marginLeft: 32 }}>
                <Input addonAfter="字符" type="number" />
              </Form.Item>
            </div>
            <Checkbox checked={keepImages} onChange={e => setKeepImages(e.target.checked)}>
              保留文档图片
            </Checkbox>
          </Card>

          <Card title="切分规则" style={{ marginBottom: 20 }}>
            <Row gutter={24}>
              <Col span={12}>
                <List
                  dataSource={ruleList}
                  style={{ maxHeight: 344, overflow: 'auto' }}
                  renderItem={item => (
                    <List.Item
                      style={{
                        padding: '8px 8px',
                        backgroundColor: '#f5f5f5',
                        borderRadius: '4px',
                        marginBottom: '8px',
                      }}
                    >
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
                        <div>
                          <Tag color={item.position === 'before' ? 'blue' : item.position === 'after' ? 'green' : 'purple'}>
                            <ScissorOutlined /> {item.position === 'before' ? '前' : item.position === 'after' ? '后' : '切分'}
                          </Tag>
                          <span style={{ fontWeight: 'bold' }}>{item.rule}</span>
                          <span style={{ fontSize: '12px', color: '#666', marginTop: 4, marginLeft: 4 }}>
                            {item.description}
                          </span>
                        </div>
                        <Button
                          type="text"
                          danger
                          icon={<DeleteOutlined />}
                          onClick={() => deleteRule(item.id)}
                          size='small'
                        />
                      </div>
                    </List.Item>
                  )}
                />
                <div style={{ marginTop: '16px' }}>
                  <p style={{ fontSize: '12px', color: '#666' }}>
                    切分优先级按展示顺序从高到低排序，可拖拽调整
                  </p>
                </div>
              </Col>

              <Col span={12}>
                <div style={{ fontSize: 12, color: '#666', marginBottom: 12 }}>
                  通用切分规则:
                </div>
                <Space wrap>
                  <Tag
                    color="blue"
                    style={{ cursor: 'pointer' }}
                    onClick={() => addPredefinedRule('\\n\\n', '双换行后切分，用于分隔段落')}
                  >
                    \n\n
                  </Tag>
                  <Tag
                    color="blue"
                    style={{ cursor: 'pointer' }}
                    onClick={() => addPredefinedRule('\\n', '单换行后切分，用于分隔普通换行')}
                  >
                    \n
                  </Tag>
                  <Tag
                    color="blue"
                    style={{ cursor: 'pointer' }}
                    onClick={() => addPredefinedRule('第.[1, 3]章', '按章节切分')}
                  >
                    第.[1, 3]章
                  </Tag>
                  <Tag
                    color="blue"
                    style={{ cursor: 'pointer' }}
                    onClick={() => addPredefinedRule('第.[1, 3]条', '按条目切分')}
                  >
                    第.[1, 3]条
                  </Tag>
                  <Tag
                    color="blue"
                    style={{ cursor: 'pointer' }}
                    onClick={() => addPredefinedRule('。', '按中文句号切分')}
                  >
                    。
                  </Tag>
                  <Tag
                    color="blue"
                    style={{ cursor: 'pointer' }}
                    onClick={() => addPredefinedRule('\\', '按反斜杠切分')}
                  >
                    \
                  </Tag>
                </Space>

                <div style={{ marginTop: 16 }}>
                  <h4 style={{ marginBottom: 12 }}>自定义规则：</h4>
                  <Input
                    placeholder="请输入正则表达式"
                    style={{ width: '200px' }}
                    value={customRule}
                    onChange={e => setCustomRule(e.target.value)}
                  />
                  <div style={{ marginTop: 12 }}>
                    <Radio.Group
                      value={rulePosition}
                      onChange={e => setRulePosition(e.target.value)}
                      buttonStyle="solid"
                      size="small"
                    >
                      <Radio.Button value="before">前</Radio.Button>
                      <Radio.Button value="after">后</Radio.Button>
                      <Radio.Button value="split">切分</Radio.Button>
                    </Radio.Group>
                    <Button
                      type="primary"
                      size="small"
                      onClick={() => addRule(customRule)}
                      disabled={!customRule}
                      style={{ marginLeft: 12 }}
                    >
                      添加
                    </Button>
                  </div>
                </div>
              </Col>
            </Row>
          </Card>

          <Card title="PDF文档解析策略" style={{ marginBottom: 20 }}>
            <Checkbox checked={enableOCR} onChange={e => setEnableOCR(e.target.checked)}>
              强制开启OCR
            </Checkbox>
            <Checkbox checked={enableFormula} onChange={e => setEnableFormula(e.target.checked)}>
              开启公式识别
            </Checkbox>
          </Card>

          <div>
            <Button type="primary" onClick={() => message.info('预览分段结果功能待实现')}>
              预览分段结果
            </Button>
          </div>
        </div>
      </div>
    );
  };

// 原文对比组件
const CompareContentStep: React.FC = () => {
  return (
    <div style={{ padding: '20px' }}>
      <div style={{ display: 'flex', height: '500px' }}>
        <div style={{ flex: 1, border: '1px solid #e8e8e8', padding: '10px', marginRight: '10px', overflow: 'auto' }}>
          <h3>原文内容</h3>
          <p>这里将显示原始文档内容...</p>
          {/* 这里应该展示原文内容 */}
        </div>
        <div style={{ flex: 1, border: '1px solid #e8e8e8', padding: '10px', overflow: 'auto' }}>
          <h3>分段结果</h3>
          <Card style={{ marginBottom: '10px' }}>
            <p>分段1 - 874 字符</p>
            <p>这里是分段后的内容片段...</p>
          </Card>
          <Card style={{ marginBottom: '10px' }}>
            <p>分段2 - 756 字符</p>
            <p>这里是分段后的内容片段...</p>
          </Card>
          {/* 这里应该展示分段结果 */}
        </div>
      </div>
    </div>
  );
};

// 数据处理组件
const ProcessDataStep: React.FC<{
  fileList: any[];
}> = ({ fileList }) => {
  return (
    <div style={{ padding: '40px 0', textAlign: 'center' }}>
      <h2>文档数据正在准备中</h2>
      <p>您可以返回知识库文件列表查看解析状态</p>

      <div style={{ margin: '40px 0' }}>
        {fileList.map((file, index) => (
          <Card key={index} style={{ marginBottom: '10px', textAlign: 'left' }}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ marginRight: '10px' }}>
                {file.type?.includes('pdf') ? '📄' : '📝'}
              </div>
              <div>
                <div>{file.name}</div>
                <div>处理中...</div>
              </div>
              <div style={{ marginLeft: 'auto' }}>
                <Button type="link" icon={<ArrowLeftOutlined />} />
              </div>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
};

const VectorItemForm: React.FC<VectorItemFormProps> = ({
  visible,
  onCancel,
  onSubmit,
  currentTable,
  vector
}) => {
  const [form] = Form.useForm();
  const [currentStep, setCurrentStep] = useState(0);
  const [fileList, setFileList] = useState<any[]>([]);
  const [splitStrategy, setSplitStrategy] = useState(vector?.splitStrategy || 0);
  const [keepImages, setKeepImages] = useState(true);
  const [enableOCR, setEnableOCR] = useState(true);
  const [enableFormula, setEnableFormula] = useState(true);
  const [ruleList, setRuleList] = useState<RuleItem[]>([
    { id: '1', rule: '\\n\\n', description: '双换行后切分，用于分隔段落', position: 'after' },
    { id: '2', rule: '\\n', description: '单换行后切分，用于分隔普通换行', position: 'after' }
  ]);
  const [fileInfo, setFileInfo] = useState<{ content: string; name: string }>({ content: '', name: '' });
  const [loading, setLoading] = useState(false);

  // 监听Modal关闭，重置表单数据
  useEffect(() => {
    if (!visible) {
      resetFormData();
    }
  }, [visible]);

  const steps = [
    {
      title: '上传文件',
      content: 'upload',
    },
    {
      title: '分段策略',
      content: 'strategy',
    },
    {
      title: '数据处理',
      content: 'process',
    },
  ];

  // 重置表单数据
  const resetFormData = () => {
    form.resetFields();
    setCurrentStep(0);
    setFileList([]);
    setFileInfo({ content: '', name: '' })
    setSplitStrategy(vector?.splitStrategy || 0);
    setKeepImages(true);
    setEnableOCR(true);
    setEnableFormula(true);
    setRuleList([
      { id: '1', rule: '\\n\\n', description: '双换行后切分，用于分隔段落', position: 'after' },
      { id: '2', rule: '\\n', description: '单换行后切分，用于分隔普通换行', position: 'after' }
    ]);
  };

  // 下一步按钮逻辑调整
  const handleNext = async () => {
    if (currentStep === 0) {
      // 步骤1校验：必须有文件内容
      if (!fileInfo.content || fileInfo.content.trim() === '') {
        message.warning('请先上传文件并成功获取内容后再进行下一步');
        return;
      }
      setCurrentStep(currentStep + 1);
    } else if (currentStep === 1) {
      // 步骤2完成后直接保存
      setLoading(true); // 开始loading
      form.validateFields().then(async (values) => {
        // 构建提交数据
        const submitData = {
          ...values,
          baseId: vector?.id,
          collectionId: currentTable?.id,
          vectorModel: vector?.vectorModel,
          dimension: vector?.dimension,
          baseType: vector?.baseType,
          splitStrategy: splitStrategy,
          maxParagraphSize: values.maxParagraphSize || vector?.maxParagraphSize,
          maxOverlapSize: values.maxOverlapSize || vector?.maxOverlapSize,
          collectionIdentifier: currentTable?.collectionIdentifier,
          isEmbedded: 0,
          deleteType: 0,
          keepImages,
          enableOCR,
          enableFormula,
          ruleList,
          content: fileInfo.content,
          name: fileInfo.name || '未命名条目',
          title: fileInfo.name || '未命名条目',
          description: values.description || '',
          fileFormat: fileList[0]?.type || '',
          status: 'active',
          sliceCount: 0,
        };
        try {
          await createKnowledgeItem(submitData);
          message.success('知识条目保存成功！');
          setCurrentStep(currentStep + 1);
        } catch (e) {
          message.error('知识条目保存失败');
        } finally {
          setLoading(false); // 无论成功失败都要关闭loading
        }
      }).catch(() => {
        setLoading(false); // 表单验证失败也要关闭loading
      });
    }
  };

  const handlePrev = () => {
    setCurrentStep(currentStep - 1);
  };

  const handleFinish = () => {
    form.validateFields().then(values => {
      // 构建提交数据
      const submitData = {
        ...values,
        // 从知识库和知识库表获取的数据
        baseId: vector?.id,
        collectionId: currentTable?.id,
        vectorModel: vector?.vectorModel,
        dimension: vector?.dimension,
        baseType: vector?.baseType,
        splitStrategy: splitStrategy,
        maxParagraphSize: values.maxParagraphSize || vector?.maxParagraphSize,
        maxOverlapSize: values.maxOverlapSize || vector?.maxOverlapSize,
        collectionIdentifier: currentTable?.collectionIdentifier,
        isEmbedded: 0,
        deleteType: 0,
        keepImages,
        enableOCR,
        enableFormula,
        ruleList
      };

      onSubmit(submitData);
      // 提交后重置表单数据
      resetFormData();
    });
  };

  // 步骤内容渲染
  const renderStepContent = () => {
    switch (currentStep) {
      case 0: // 上传文件
        return <FileUploadStep fileContent={fileInfo.content} setFileInfo={setFileInfo} />;
      case 1: // 分段策略
        return (
          <SplitStrategyStep
            vector={vector}
            ruleList={ruleList}
            setRuleList={setRuleList}
            keepImages={keepImages}
            setKeepImages={setKeepImages}
            enableOCR={enableOCR}
            setEnableOCR={setEnableOCR}
            enableFormula={enableFormula}
            setEnableFormula={setEnableFormula}
          />
        );
      case 2: // 数据处理
        return <ProcessDataStep fileList={fileList} />;
      default:
        return null;
    }
  };

  // 处理Modal取消
  const handleCancel = () => {
    resetFormData();
    onCancel();
  };

  return (
    <Modal
      title="新建知识条目"
      open={visible}
      onCancel={loading ? undefined : handleCancel}
      width="95vw"
      style={{ top: 20 }}
      maskClosable={loading ? false : false}
      keyboard={loading ? false : false}
      styles={{
        body: {
          height: 'calc(100vh - 160px)',
          overflow: 'auto',
          padding: '24px',
          borderBottom: '1px solid #f0f0f0',
        }
      }}
      footer={
        <div className="steps-action" style={{
          display: 'flex',
          justifyContent: 'end',
          gap: 12,
          padding: '0 24px',
        }}
        >
          {(currentStep > 0 && currentStep < steps.length - 1)  && (
            <Button onClick={handlePrev} disabled={loading}>
              上一步
            </Button>
          )}
          {currentStep === 0 && (
            <Button onClick={handleCancel} disabled={loading}>
              取消
            </Button>
          )}
          <div>
            {currentStep < steps.length - 1 && (
              <Button type="primary" onClick={handleNext} loading={loading} disabled={loading}>
                {loading ? '保存中...' : '下一步'}
              </Button>
            )}
            {currentStep === steps.length - 1 && (
              <Button type="primary" onClick={handleFinish} disabled={loading}>
                返回知识库
              </Button>
            )}
          </div>
        </div>
      }
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleFinish}
      >
        <Steps current={currentStep} style={{ marginBottom: '30px' }}>
          {steps.map(item => (
            <Step key={item.title} title={item.title} />
          ))}
        </Steps>

        <div className="steps-content" style={{ position: 'relative' }}>
          {renderStepContent()}
          {loading && (
            <div style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              backgroundColor: 'rgba(255, 255, 255, 0.8)',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              zIndex: 1000,
              borderRadius: '6px'
            }}>
              <div style={{ textAlign: 'center' }}>
                <Spin size="large" indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />} />
                <div style={{ marginTop: 16, fontSize: 16, color: '#666' }}>
                  正在保存知识条目，请稍候...
                </div>
              </div>
            </div>
          )}
        </div>
      </Form>
    </Modal>
  );
};

export default VectorItemForm; 